<?php

namespace Iwester\Http\Controllers\Auth;

use Iwester\Http\Model\User\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Iwester\Http\Requests\UserCreateRequest;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * 注册用户
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function register(UserCreateRequest $request)
    {
        try {
            \DB::beginTransaction();
            $vercode = $request->get('vercode', '');
            $type = $request->get('type', 'register');
            if ($vercode == '') return ['code' => 201, 'message' => '请输入正确验证码'];
            $data = $request->get('user', []);
            $checkVercode = $this->checkVercode($request->get('_token', false), $data['email'], $type, $vercode);
            if (!$checkVercode) return ['code' => 201, 'message' => '验证码错误！'];
            $password = $data['password'];
            $data['uuid'] = \Faker\Provider\Uuid::uuid();
            $data['password'] = bcrypt($data['password']);
            $data['name'] = $data['username'];
            $data['phone'] = '';
            $user = User::create($data);
            $user->syncRoles([3]); # 分配游客角色
            \DB::commit();
            \Auth::attempt(['username' => $data['username'], 'password' => $password]);
            return ['code' => 200, 'message' => '注册成功，正在登陆...'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => '注册失败！'];
        }
    }

    /**
     * 验证验证码
     * @param $token
     * @param $email
     * @param $vercode
     * @return bool
     */
    public function checkVercode($token, $email, $type, $vercode){
        return true;
        $key = $email.$token.$type;
        $cacheVercode = \Cache::pull($key);
        if ($vercode == $cacheVercode){
            return true;
        }
        return false;
    }
}
